/*
 * @Author: malgee
 * @Date: 2025-04-23 13:49:53
 * @LastEditors: maling
 * @LastEditTime: 2025-04-27 11:14:34
 * @FilePath: /vue3-ts-cms/src/store/login/login.ts
 * @Description: 
 * 
 */
import { Module } from "vuex";
import { IRootState } from "../types";
import { ILoginState } from "./types";
import { IAccount } from "@/service/login/types";
import { fetchAccountLogin, fetchUserInfo, fetchUserMenusById } from "@/service/login/login";
import router from "@/router";
import localCache from "@/utils/cache";
import { loadDynamicRoutes, mapMenusToPermissions} from "@/utils/map-menus";

export default {
  // 模块命名空间, 避免命名冲突
  namespaced: true,
  state: {
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  },
  mutations: {
    setToken(state, token: string) {
      state.token = token
    },
    setUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    setUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // 注册动态路由
      const routes = loadDynamicRoutes(userMenus)
      
      // 添加动态路由
      routes.forEach(route => {
        router.addRoute('main', route)
      })

      console.log('获取用户的routes>>>>>>>>', routes);

      // 获取用户按钮权限
      const permissions = mapMenusToPermissions(userMenus)
      console.log('获取用户按钮权限', permissions);
      state.permissions = permissions
    }
  },
  actions: {
    async accountLogin({ commit, dispatch }, payload: IAccount) {

      // 1. 实现登录
      const res = await fetchAccountLogin(payload)
      const { id, token } = res.data
      commit('setToken', token)
      localCache.set('token', token)

      // 发送初始化请求, 获取完整的 role/department
      dispatch('getInitialDataAction', null, { root: true })
      
      // 2. 获取用户信息
      const userInfoRes = await fetchUserInfo(id)
      const userInfo = userInfoRes.data
      commit('setUserInfo', userInfo)
      localCache.set('userInfo', userInfo)

      // 3. 获取用户菜单
      const userMenusRes = await fetchUserMenusById(userInfo.role.id)
      const userMenus = userMenusRes.data
      commit('setUserMenus', userMenus)
      localCache.set('userMenus', userMenus)

      // 4. 登录成功,跳转到首页
      router.push('/main')
    },

    async loadLocalLogin({ commit, dispatch }) {
      const token = localCache.get('token')
      if (token) {
        commit('setToken', token)

        // 发送初始化请求, 获取完整的 role/department
        dispatch('getInitialDataAction', null, { root: true })
      }

      // 2. 获取用户信息
      const userInfo = localCache.get('userInfo')
      if (userInfo) {
        commit('setUserInfo', userInfo)
      }

      // 3. 获取用户菜单
      const userMenus = localCache.get('userMenus')
      if (userMenus) {
        commit('setUserMenus', userMenus)
      } 
    }
  },
  getters: {}
} as Module<ILoginState, IRootState>
